//
//  WmcCloudSearchPhotoVC.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/31.
//

import UIKit

// MARK: - 扩展WmcCloudSearchPhotoVC + WmcNavigatorProtocol

extension WmcCloudSearchPhotoVC: WmcNavigatorProtocol {
    static func navigationPaths() -> [WmcNavigatorManager.Path] {
        return [.cloudScreenPhoto]
    }

    static func willMakeNavigationVC(with parms: WmcNavigatorManager.Parms) -> UIViewController {
        let vm = WmcCloudSearchPhotoVM()
        let vc = WmcCloudSearchPhotoVC(vm)
        return vc
    }
}

// MARK: - 扩展WmcCloudSearchPhotoVC + WmcVMProtocol

extension WmcCloudSearchPhotoVC: WmcVMProtocol {
    typealias VMType = WmcCloudSearchPhotoVM
}

// MARK: - [WmcCloudSearchPhotoVC]

class WmcCloudSearchPhotoVC: WmcBaseVC {
    // Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()

        viewModel.loadList()
    }

    // Internal

    override func makeUI() {
        makeNavView(showShadow: false)
        title = "查找照片"

        addSubview(line)
        addSubview(tableView)

        line.snp.makeConstraints { make in
            make.top.equalTo(navView.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(1)
        }

        tableView.snp.makeConstraints { make in
            make.top.equalTo(line.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
    }

    override func bindViewModel() {
        viewModel.dataListRelay.subscribe(onNext: { [weak self] list in
            guard let weakSelf = self else { return }
            weakSelf.tableView.reloadData()
        }).disposed(by: rx.disposeBag)

        tableFooterView.queryClosure = { [weak self] in
            guard let weakSelf = self else { return }
            let vm = WmcCloudAlbumSearchResultVM()
            vm.startDate = weakSelf.viewModel.startDateModel.disTitle
            vm.endDate = weakSelf.viewModel.endDateModel.disTitle
            vm.watermarks = weakSelf.viewModel.selectedWatermarks
            WmcNavigatorManager.push(.searchPhotoResult, parms: vm)
        }
    }

    // Private

    private lazy var tableView: UITableView = {
        let tableView = UITableView.YP.Create(style: .plain, delegate: self, dataSource: self, registers: [
            YPRegister(WmcCloudSearchPhotoCell.self),
        ])
        tableView.tableFooterView = tableFooterView
        tableView.rowHeight = 57
        return tableView
    }()

    private lazy var tableFooterView: WmcCloudSearchPhotoFooterView = {
        let view = WmcCloudSearchPhotoFooterView(frame: CGRect(x: 0,
                                                               y: 0,
                                                               width: Wmc_screenWidth,
                                                               height: 85))
        return view
    }()

    private lazy var line: UIView = {
        let view = UIView()
        view.backgroundColor = .wmc_grayH15_E6E6E6
        return view
    }()

    private func selectCalendarDate(type: WmcCloudSearchPhotoVM.CellModel.ActionType) {
        let datePickerView = WmcDatePickerView()
        if type == .startDate {
            datePickerView.dateStr = viewModel.startDateModel.disTitle
        } else if type == .endDate {
            datePickerView.dateStr = viewModel.endDateModel.disTitle
        }

        datePickerView.sureClosure = { [weak self] text in
            guard let weakSelf = self else { return }
            if type == .startDate {
                if let startDate = text.replacingOccurrences(of: ".", with: "-").yp.date(format: .iso8601Day, identifier: .asia(.Shanghai)), let endDate = weakSelf.viewModel.endDateModel.disTitle.replacingOccurrences(of: ".", with: "-").yp.date(format: .iso8601Day, identifier: .asia(.Shanghai)) {
                    if startDate.timeIntervalSince1970 <= endDate.timeIntervalSince1970 {
                        weakSelf.viewModel.startDateModel.disTitle = text
                    } else {
                        WmcHudManager.toast("开始时间不能早于结束时间")
                    }
                }
            } else if type == .endDate {
                if let startDate = weakSelf.viewModel.startDateModel.disTitle.replacingOccurrences(of: ".", with: "-").yp.date(format: .iso8601Day, identifier: .asia(.Shanghai)), let endDate = text.replacingOccurrences(of: ".", with: "-").yp.date(format: .iso8601Day, identifier: .asia(.Shanghai)) {
                    if startDate.timeIntervalSince1970 <= endDate.timeIntervalSince1970 {
                        weakSelf.viewModel.endDateModel.disTitle = text
                    } else {
                        WmcHudManager.toast("开始时间不能早于结束时间")
                    }
                }
            }
            weakSelf.tableView.reloadData()
        }

        let presentVC = WmcPresentVC(config: .init(style: .sheet(),
                                                   contentView: datePickerView,
                                                   contentLayoutBlock: { make in
                                                       let height = 250 + Wmc_safeAreaBottom
                                                       make.left.right.bottom.equalToSuperview()
                                                       make.height.equalTo(height)
                                                   }))
        presentVC.show()
    }

    private func fetchWatermarkList(completion: @escaping ([WmcSelectWatermarkModel]) -> Void, failure: @escaping (Error?) -> Void) {
        WmcMediaAlbumAPI.fetchTakePhotoStatistics().subscribe(onNext: { [weak self] list in
            guard let weakSelf = self else { return }
            let dataSource: [WmcSelectWatermarkModel] = list.map { model -> WmcSelectWatermarkModel in
                let r = WmcSelectWatermarkModel()
                r.data = model
                r.isSelected = weakSelf.judgeModelIsSelected(model: model)
                return r
            }
            completion(dataSource)
        }, onError: { error in
            failure(error)
        }).disposed(by: rx.disposeBag)
    }

    private func judgeModelIsSelected(model: WmcMediaPhotographStatisticsModel) -> Bool {
        var isSelected: Bool = false
        for (_, item) in viewModel.selectedWatermarks.enumerated() {
            if model.wmId == item.data.wmId {
                isSelected = true
                break
            }
        }
        return isSelected
    }

    private func pushSelectWatermarkVC() {
        WmcHudManager.loading()
        fetchWatermarkList { [weak self] list in
            guard let weakSelf = self else { return }
            WmcHudManager.dismiss()
            weakSelf.viewModel.allWatermarks = list

            if list.isEmpty {
                WmcHudManager.toast("没有使用过的水印")
            } else {
                let viewModel = WmcSelectWatermarkVM()
                viewModel.watermarks = weakSelf.viewModel.allWatermarks

                viewModel.ensureClosure = { [weak self] list in
                    guard let weakSelf = self else { return }
                    weakSelf.viewModel.selectedWatermarks = list
                    if list.isEmpty {
                        weakSelf.viewModel.watermarkModel.disTitle = "选择水印"
                        weakSelf.viewModel.watermarkModel.disTitleColor = .wmc_grayH8_8A8A99
                    } else {
                        var titles: [String] = []
                        list.forEach { model in
                            titles.append(model.data.name)
                        }
                        let text = titles.joined(separator: "，")
                        weakSelf.viewModel.watermarkModel.disTitle = text
                        weakSelf.viewModel.watermarkModel.disTitleColor = .wmc_grayH2_323233
                    }
                    weakSelf.tableView.reloadData()
                }
                WmcNavigatorManager.push(.selectWatermark, parms: viewModel)
            }
        } failure: { error in
            WmcHudManager.dismiss()
            WmcHudManager.toast(error)
        }
    }
}

// MARK: - UITableViewDelegate

extension WmcCloudSearchPhotoVC: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let group = viewModel.dataListRelay.value.yp.object(at: indexPath.section),
              let model = group.yp.object(at: indexPath.row) else { return }
        switch model.actionType {
        case .startDate,
             .endDate:
            selectCalendarDate(type: model.actionType)
        case .watermark:
            pushSelectWatermarkVC()
        }
    }
}

// MARK: - UITableViewDataSource

extension WmcCloudSearchPhotoVC: UITableViewDataSource {
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return .YP.Min
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return viewModel.dataListRelay.value.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let group = viewModel.dataListRelay.value.yp.object(at: section) {
            return group.count
        }
        return 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: WmcCloudSearchPhotoCell = tableView.yp.dequeueReusableCell()
        if let group = viewModel.dataListRelay.value.yp.object(at: indexPath.section),
           let model = group.yp.object(at: indexPath.row)
        {
            cell.configModel(model)
        }
        return cell
    }
}
